package com.modular.iot.opt;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.c.opt.ComOpt;
import com.modular.iot.bean.DataFactorDo;
import com.tool.ToolRedisson;
import org.redisson.api.RBucket;

import java.time.Duration;

public class OptDataFactorCom extends ComOpt<DataFactorDo> {

    public OptDataFactorCom() {
        super("data_factor");
    }

    /**
     * 通过因子名称获取因子对象 - 找不到自动补充异常编码数据到数据库
     * @param factorCode
     * @return
     */
    public DataFactorDo getByCode(String factorCode) {
        RBucket<DataFactorDo> bucket = ToolRedisson.me.redisson.getBucket(StrUtil.format("com-data-factor-{}", factorCode));
        if (!bucket.isExists()) {
            DataFactorDo dataFactorDo = getBean(query().eq("code", factorCode)
                .orEq("old_code", factorCode).orLike("ext_codes", factorCode));
            if (ObjectUtil.isNull(dataFactorDo)) {
                dataFactorDo = new DataFactorDo();
                dataFactorDo.setCode(factorCode);
                dataFactorDo.setName("未知编码-" + factorCode);
                dataFactorDo.setId(syncBean(dataFactorDo));
            }
            bucket.set(dataFactorDo, Duration.ofSeconds(60 * 10));
        }
        return bucket.get();
    }

}
